package org.easyframework.redis.config;

import java.util.HashSet;
import java.util.Set;

import org.easyframework.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import redis.clients.jedis.JedisPoolConfig;

/**
 * @ClassName: RedisConfig
 * @Description: redis 配置类
 * @author: daiw
 * @date: 2019年10月15日 下午3:00:35
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
	private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

	@Value("${redis.hostname}")
	private String hostname;

	@Value("${redis.port}")
	private Integer port;

	@Value("${redis.password}")
	private String password;

	@Value("${redis.maxIdle}")
	private Integer maxIdle;

	@Value("${redis.maxTotal}")
	private Integer maxTotal;

	@Value("${redis.maxWaitMillis}")
	private Integer maxWaitMillis;

	@Value("${redis.minEvictableIdleTimeMillis}")
	private Integer minEvictableIdleTimeMillis;

	@Value("${redis.numTestsPerEvictionRun}")
	private Integer numTestsPerEvictionRun;

	@Value("${redis.timeBetweenEvictionRunsMillis}")
	private long timeBetweenEvictionRunsMillis;

	@Value("${redis.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${redis.testWhileIdle}")
	private boolean testWhileIdle;

	@Value("${spring.redis.cluster.nodes}")
	private String clusterNodes;

	@Value("${spring.redis.cluster.max-redirects}")
	private Integer mmaxRedirectsac;

	@Value("${redis.mode}")
	private Integer model;

	/**
	 * JedisPoolConfig 连接池
	 * 
	 * @return
	 */
	@Bean
	public JedisPoolConfig jedisPoolConfig() {
		logger.info("注入JedisPoolConfig");
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		// 最大空闲数
		jedisPoolConfig.setMaxIdle(maxIdle);
		// 连接池的最大数据库连接数
		jedisPoolConfig.setMaxTotal(maxTotal);
		// 最大建立连接等待时间
		jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
		// 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
		jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		// 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
		jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
		// 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
		jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		// 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
		jedisPoolConfig.setTestOnBorrow(testOnBorrow);
		// 在空闲时检查有效性, 默认false
		jedisPoolConfig.setTestWhileIdle(testWhileIdle);
		return jedisPoolConfig;
	}

	@Bean
	public RedisClusterConfiguration getRedisClusterConfiguration() {
		if (model != 2) {
			return null;
		}
		logger.info("注入RedisClusterConfiguration");
		RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
		clusterConfig.setMaxRedirects(mmaxRedirectsac);
		String[] serverArray = clusterNodes.split(",");
		Set<RedisNode> nodes = new HashSet<>();
		for (String server : serverArray) {
			String[] ipAndPortArray = server.split(":");
			nodes.add(new RedisNode(ipAndPortArray[0].trim(), Integer.parseInt(ipAndPortArray[1].trim())));
		}
		clusterConfig.setClusterNodes(nodes);
		return clusterConfig;
	}

	/**
	 * 单机版配置 @Title: JedisConnectionFactory @param @param
	 * jedisPoolConfig @param @return @return JedisConnectionFactory @date
	 * 2018年2月24日 @throws
	 */
	@Bean
	public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
		JedisConnectionFactory JedisConnectionFactory = null;
		String modelString = null;
		if (model == 1) {// 单机模式
			JedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
			// IP地址
			JedisConnectionFactory.setHostName(hostname);
			// 端口号
			JedisConnectionFactory.setPort(port);
			modelString = "单机模式";
		} else if (model == 2) {// 集群模式
			JedisConnectionFactory = new JedisConnectionFactory(getRedisClusterConfiguration(), jedisPoolConfig);
			modelString = "集群模式";
		} else {
			throw new RuntimeException("未知的redis模式，1 单机模式，2 集群模式");
		}
		// 如果Redis设置有密码
		if (!StringUtils.isEmpty(password)) {
			JedisConnectionFactory.setPassword(password);
		}
		// 客户端超时时间单位是毫秒
		JedisConnectionFactory.setTimeout(5000);
		logger.info("完成redis连接初始化，当前模式：" + modelString);
		return JedisConnectionFactory;
	}

	/**
	 * 实例化 RedisTemplate 对象
	 *
	 * @return
	 */
	@Bean
	public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
		return redisTemplate;
	}

	/**
	 * 设置数据存入 redis 的序列化方式,并开启事务
	 * 
	 * @param redisTemplate
	 * @param factory
	 */
	private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
		// 如果不配置Serializer，那么存储的时候缺省使用String，如果用User类型存储，那么会提示错误User can't cast
		// to String！
		redisTemplate.setKeySerializer(new StringRedisSerializer());//
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());

		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());

		// 开启事务
		redisTemplate.setEnableTransactionSupport(true);
		redisTemplate.setConnectionFactory(factory);
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(factory);
		return stringRedisTemplate;
	}

	/**
	 * 注入封装RedisTemplate @Title: redisUtil @return RedisUtil @date
	 * 2017年12月21日 @throws
	 */
	@Bean(name = "redisUtil")
	public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
		RedisUtil redisUtil = new RedisUtil();
		redisUtil.setRedisTemplate(redisTemplate);
		redisUtil.setStringRedisTemplate(stringRedisTemplate);
		redisUtil.setHostName(hostname);
		return redisUtil;
	}
}
